package com.apollo.es;
import com.selft.EsClientFacotory;
import util.DateUtil;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import util.FileUtil;

import java.io.File;
import java.util.*;

/**
 * Created by Administrator on 2018/2/2.
 */
public class QueryRemoteLogManager {

    /**
     * 获取所有index
     */
    public static Set getAllIndices(Client client) {
        ActionFuture<IndicesStatsResponse> isr = client.admin().indices().stats(new IndicesStatsRequest().all());
        IndicesAdminClient indicesAdminClient = client.admin().indices();
        Map<String, IndexStats> indexStatsMap = isr.actionGet().getIndices();
        Set<String> setA = isr.actionGet().getIndices().keySet();
        Set<String> msSet = new HashSet<String>();
        Iterator<String> iterator = setA.iterator();
        while (iterator.hasNext()){
            String set =  iterator.next();
            System.out.println("set=="+set);
            if(!set.contains("ms-v10") && set.contains("ms-")){
                msSet.add(set.toLowerCase());
            }
        }
        System.out.println("size:"+msSet.size());
        return msSet;
    }

    public static void main(String[] args)throws  Exception{
        final Client client = EsClientFacotory.getInstance();
        Set<String> set =  getAllIndices(client);

        List<String> localService = FileUtil.readTxt(new File("e:/service.txt"));

        for(String a : localService){
            if(set.contains("ms-"+a.trim().toLowerCase())){
                //System.out.println("content:"+a);
            }else{
                System.out.println("content2:"+a);
            }
        }

        for(String s : set){
            System.out.println("s==="+s);
            final String indexName = s;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    RestTemplateTest.queryData(indexName);
                }
            }).start();
        }
       client.close();

    }


    //搜索查询
    public static void search(Client client,String indexName,String type){
//        SearchRequestBuilder srb1 = client
//                .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setFrom(0).setSize(100);
        QueryBuilder m4 = null ;
        try {
            //1514131758175
            long time = DateUtil.convertStringToDate("yyyy-MM-dd HH:mm:ss","2018-02-01 20:00:00").getTime();
            long end = DateUtil.convertStringToDate(DateUtil.YYYY_MM_DD_HH_MM_SS,"2018-02-03 19:00:00").getTime();
            System.out.println("time=="+time);
            m4 = QueryBuilders.rangeQuery("id").gte(time).lte(end);
        } catch (Exception e) {
            e.printStackTrace();
        }
        QueryBuilder m6 = QueryBuilders.termQuery("level", "ERROR");
        QueryBuilder m5 = QueryBuilders.wildcardQuery("thrown","*ClientHandlerException*");
        QueryBuilder m7 = QueryBuilders.termQuery("traceId", "1b6296ad70139e45");

        BoolQueryBuilder totalQuery = QueryBuilders.boolQuery();
        totalQuery.must(m4);//这种查询不行，只会查询must的匹配

        System.out.print(totalQuery.toString());

        //必须外面套一层must

        //and搜索条件
        SearchRequestBuilder searchRequestBuilder =client.prepareSearch(indexName).setTypes(type);
        SearchResponse searchResponse =searchRequestBuilder
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setFrom(0).setSize(10000).setExplain(false)
                .setQuery(m4)
                .execute()
                .actionGet();
        SearchHits hits = searchResponse.getHits();
        long record = 0;
        long totalCount = hits.getHits().length;
        long allCount = hits.totalHits();
        System.out.println("totalCount:"+totalCount+",allCount="+allCount);
        for (int i = 0; i < totalCount; i++) {
            Map map = hits.getAt(i).getSource();
            System.out.println("<<<<<<thrown:"+map.get("thrown"));
        }

//        SearchRequestBuilder srb2 = client
//                .prepareSearch().setQuery(totalQuery).setFrom(0).setSize(10000);
//
//        MultiSearchResponse sr = client.prepareMultiSearch()
//                .add(srb2)
//                .get();
//        // You will get all individual responses from MultiSearchResponse#getResponses()
//        long nbHits = 0;
//        for (MultiSearchResponse.Item item : sr.getResponses()) {
//            SearchResponse response = item.getResponse();
//            if(response!=null){
//                SearchHits hits = response.getHits();
//                long record = 0;
//                long totalCount = hits.getHits().length;
//                long allCount = hits.totalHits();
//                System.out.println("totalCount:"+totalCount+",allCount="+allCount);
//                for (int i = 0; i < totalCount; i++) {
//                    Map map = hits.getAt(i).getSource();
//                    System.out.println("<<<<<<thrown:"+map.get("thrown"));
//                }
//                nbHits += response.getHits().getTotalHits();
//            }else{
//                System.out.println("))))");
//            }
//        }
        //System.out.println(nbHits);
    }

}
